package com.xnyzc.lhy.mis.service.impl.cms.driver;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.penum.driver.EServiceFraction;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.mis.entity.order.OaDOrder;
import com.xnyzc.lhy.mis.entity.result.cms.driver.CmsDriverWorkStatisticsRes;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.user.OaDUserInfo;
import com.xnyzc.lhy.mis.entity.work.OaDWorkRecord;
import com.xnyzc.lhy.mis.mapper.cms.driver.DriverWorkStatisticsMapper;
import com.xnyzc.lhy.mis.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.work.OaDWorkRecordMapper;
import com.xnyzc.lhy.mis.service.cms.driver.IDriverWorkStatisticsService;
import com.xnyzc.lhy.mis.service.cms.util.IOaSysGetOfficeIdListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 司机统计
 * @Author zhuyubin
 * @Date 2019-08-27 22:03
 **/
@Service
public class DriverWorkStatisticsServiceImpl implements IDriverWorkStatisticsService {

    private static final String ZERO = "0";

    @Autowired
    private DriverWorkStatisticsMapper driverWorkStatisticsMapper;
    @Autowired
    private IOaSysGetOfficeIdListService iOaSysGetOfficeIdListService;
    @Autowired
    private OaDUserMapper oaDUserMapper;
    @Autowired
    private OaDOrderMapper oaDOrderMapper;
    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;
    @Autowired
    private OaDWorkRecordMapper oaDWorkRecordMapper;

    /**
     * 司机工作统计
     * @param sysUserId 后台用户id
     * @param tag 租户
     * @param current 当前页
     * @param name 司机名
     * @return
     */
    @Override
    public IPage<CmsDriverWorkStatisticsRes> selectDriverWorkStatisticsPage(Long sysUserId, List<String> type, String tag, Long current, String name, String phone){
        BigDecimal zero = new BigDecimal("0");
        IPage<CmsDriverWorkStatisticsRes> cmsDriverWorkStatisticsResIPage = new Page<>();
        List<CmsDriverWorkStatisticsRes> cmsDriverWorkStatisticsResList = new ArrayList<>();
        List<Long> driverIds = iOaSysGetOfficeIdListService.selectDUserIdList(sysUserId, type);
        IPage<OaDUser> oaDUserIPage = new Page<>();
        oaDUserIPage.setSize(20L);
        oaDUserIPage.setCurrent(current);
        // 司机信息
        LambdaQueryWrapper<OaDUser> oaDUserLambdaQW = Wrappers.<OaDUser>lambdaQuery()
                .eq(OaDUser::getTag, tag)
                .in(OaDUser::getDriverId, driverIds)
                .orderByDesc(OaDUser::getCreateTime);
        if (CheckUtil.objIsNotEmpty(name)){
            oaDUserLambdaQW.like(OaDUser::getDriverName, name);
        }
        if (CheckUtil.objIsNotEmpty(phone)){
            oaDUserLambdaQW.like(OaDUser::getDriverPhone, phone);
        }
        oaDUserIPage = oaDUserMapper.selectPage(oaDUserIPage, oaDUserLambdaQW);
        List<OaDUser> oaDUserList = oaDUserIPage.getRecords();
        driverIds = new ArrayList<>();
        for (OaDUser oaDUser : oaDUserList) {
            CmsDriverWorkStatisticsRes cmsDriverWorkStatisticsRes = new CmsDriverWorkStatisticsRes();
            cmsDriverWorkStatisticsRes.setDriverId(oaDUser.getDriverId());
            cmsDriverWorkStatisticsRes.setDriverName(oaDUser.getDriverName());
            cmsDriverWorkStatisticsRes.setDriverPhone(oaDUser.getDriverPhone());
            cmsDriverWorkStatisticsResList.add(cmsDriverWorkStatisticsRes);
            driverIds.add(oaDUser.getDriverId());
        }
        // 司机全部订单
        List<OaDOrder> oaDOrderList = oaDOrderMapper.selectList(
                Wrappers.<OaDOrder>lambdaQuery()
                        .eq(OaDOrder::getTag, tag)
                        .eq(OaDOrder::getOrderStatus, EOrderStatus.paymented.getType())
                        .in(OaDOrder::getDriverId, driverIds)
                        .orderByDesc(OaDOrder::getDriverId));
        // 司机详细信息
        List<OaDUserInfo> oaDUserInfoList = oaDUserInfoMapper.selectList(
                Wrappers.<OaDUserInfo>lambdaQuery()
                        .eq(OaDUserInfo::getTag, tag)
                        .in(OaDUserInfo::getDriverId, driverIds)
                        .orderByDesc(OaDUserInfo::getCreateTime));
        List<OaDWorkRecord> oaDWorkRecordList = oaDWorkRecordMapper.selectList(
                Wrappers.<OaDWorkRecord>lambdaQuery()
                        .eq(OaDWorkRecord::getTag, tag)
                        .in(OaDWorkRecord::getDriverId, driverIds)
                        .orderByDesc(OaDWorkRecord::getDriverId)
                        .orderByDesc(OaDWorkRecord::getCreateTime));
        for (CmsDriverWorkStatisticsRes cmsDriverWorkStatisticsRes : cmsDriverWorkStatisticsResList) {
            Long driverId = cmsDriverWorkStatisticsRes.getDriverId();
            // 全部收入
            BigDecimal dayTotalCost = zero;
            // 全部接单数
            Integer dayOrderNumber = 0;
            for (OaDOrder oaDOrder : oaDOrderList) {
                if (!driverId.equals(oaDOrder.getDriverId())){
                    continue;
                }
                BigDecimal drawFee = oaDOrder.getDrawFee();
                if (CheckUtil.objIsEmpty(drawFee)){
                    continue;
                }
                dayTotalCost = dayTotalCost.add(drawFee);
                dayOrderNumber += 1;
            }
            cmsDriverWorkStatisticsRes.setDayTotalCost(dayTotalCost);
            cmsDriverWorkStatisticsRes.setDayOrderNumber(dayOrderNumber);
            // 服务分
            for (OaDUserInfo oaDUserInfo : oaDUserInfoList) {
                if (!driverId.equals(oaDUserInfo.getDriverId())){
                    continue;
                }
                Integer totalServiceScore = oaDUserInfo.getTotalServiceScore();
                if (CheckUtil.objIsNotEmpty(totalServiceScore)){
                    cmsDriverWorkStatisticsRes.setTotalServiceScore(totalServiceScore);
                } else {
                    cmsDriverWorkStatisticsRes.setTotalServiceScore(EServiceFraction.serviceFraction.getValue());
                }
            }
            // 总在线时长
            Long min = 0L;
            if (CheckUtil.objIsNotEmpty(oaDWorkRecordList)) {
                for (int i = 0; i < oaDWorkRecordList.size(); i++) {
                    OaDWorkRecord oaDWorkRecord = oaDWorkRecordList.get(i);
                    if (CheckUtil.objIsEmpty(oaDWorkRecord)){
                        continue;
                    }
                    if (!driverId.equals(oaDWorkRecord.getDriverId())){
                        continue;
                    }
                    // 开始接单时间
                    Date startTime = oaDWorkRecord.getStartTime();
                    if (CheckUtil.objIsEmpty(startTime)) {
                        continue;
                    }
                    // 结束接单时间
                    Date endTime = oaDWorkRecord.getEndTime();
                    if (CheckUtil.objIsEmpty(endTime)) {
                        continue;
                    }
                    min = min + DateUtil.dateSubtractLong(startTime, endTime);
                }
                OaDWorkRecord oaDWorkRecord = oaDWorkRecordList.get(oaDWorkRecordList.size() - 1);
                if (CheckUtil.objIsEmpty(oaDWorkRecord.getEndTime())) {
                    Date startTime = oaDWorkRecord.getStartTime();
                    if (CheckUtil.objIsNotEmpty(startTime)) {
                        min = min + DateUtil.dateSubtractLong(startTime, new Date());
                    }
                }
                String h = this.minToHour(min);
                cmsDriverWorkStatisticsRes.setDayOrderTime(h);
            }
        }
        cmsDriverWorkStatisticsResIPage.setPages(oaDUserIPage.getPages());
        cmsDriverWorkStatisticsResIPage.setRecords(cmsDriverWorkStatisticsResList);
        cmsDriverWorkStatisticsResIPage.setTotal(oaDUserIPage.getTotal());
        cmsDriverWorkStatisticsResIPage.setSize(oaDUserIPage.getSize());
        cmsDriverWorkStatisticsResIPage.setCurrent(oaDUserIPage.getCurrent());
        /*QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(String.format("odu.%s", OaDUser.TAG), tag);
        queryWrapper.in(String.format("odu.%s", OaDUser.DRIVER_ID), driverIds);
        queryWrapper.groupBy(String.format("odu.%s", OaDUser.DRIVER_ID));
        queryWrapper.orderByDesc(String.format("odu.%s", OaDUser.CREATE_TIME));
        if (CheckUtil.objIsNotEmpty(name)){
            queryWrapper.like(String.format("odu.%s", OaDUser.DRIVER_NAME), name);
        }
        if (CheckUtil.objIsNotEmpty(phone)){
            queryWrapper.like(String.format("odu.%s", OaDUser.DRIVER_PHONE), phone);
        }
        IPage<CmsDriverWorkStatisticsRes> cmsDriverWorkStatisticsResIPage = new Page<>();
        cmsDriverWorkStatisticsResIPage.setCurrent(current);
        return driverWorkStatisticsMapper.selectDriverWorkStatisticsPage(cmsDriverWorkStatisticsResIPage, queryWrapper);*/
        return cmsDriverWorkStatisticsResIPage;
    }

    /**
     * 分钟转小时
     * @param min 分钟
     * @return
     */
    private String minToHour(Long min){
        // 分钟转小时保留一位小数
        String minStr = min.toString();
        if (!ZERO.equals(minStr)) {
            BigDecimal six = new BigDecimal("60");
            BigDecimal mainBig = new BigDecimal(minStr);
            BigDecimal h = mainBig.divide(six, 1, BigDecimal.ROUND_HALF_UP);
            String hStr = h.toString();
            if (hStr.contains(".0")) {
                String[] hSplit = hStr.split("\\.");
                return hSplit[0];
            } else {
                return hStr;
            }
        } else {
            return ZERO;
        }
    }
}
